package com.electric.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.electric.common.CommonStringUtils;
import com.electric.common.Contains;
import com.electric.common.LoggerInterface;
import com.electric.entity.Attachment;
import com.electric.entity.CustomRepairRecord;
import com.electric.entity.Customer;
import com.electric.entity.RepairRecord;
import com.electric.entity.RepairRecordParameter;
import com.electric.entity.RepairType;
import com.electric.entity.VoltageLevel;
import com.electric.service.IAttachmentService;
import com.electric.service.ICustomerService;
import com.electric.service.IRepairRecordParameterService;
import com.electric.service.IRepairRecordService;
import com.electric.service.IRepairTypeService;
import com.electric.service.IVoltageLevelService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * <p>
 * 故障记录 前端控制器
 * </p>
 *
 * @author zhangbin
 * @since 2018-08-28
 */
@Controller
@RequestMapping("/repairRecord")
public class RepairRecordController implements LoggerInterface {
	@Autowired
	private IRepairRecordService repairRecordService;
	@Autowired
	private IRepairRecordParameterService recordParameterService;
	@Autowired
	private IAttachmentService attachmentService;
	@Autowired
	private IVoltageLevelService voltageLevelService;
	@Autowired
	private IRepairTypeService repairTypeService;
	@Autowired
	private ICustomerService customerService;
	
	private static final String CALCULATE_EXPORT_FILE_NAME = "计算过程.txt";

	@RequestMapping("/init")
	public ModelAndView init() {
		ModelAndView view = list(1, 0, null, null, null, null, null, null, null);
		view.setViewName("/repairRecord/init");

		List<RepairType> allRepairType = repairTypeService.selectAllRepairType();
		List<VoltageLevel> allVoltageLevel = voltageLevelService.selectAllVoltageLevel();

		view.addObject("allRepairType", allRepairType);
		view.addObject("allVoltageLevel", allVoltageLevel);

		return view;
	}

	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(defaultValue = "1", name = "pageNum") int pageNum,
			@RequestParam(defaultValue = "0") int pageSize, @RequestParam(required = false) String customerName,
			@RequestParam(required = false) String repairType, @RequestParam(required = false) String voltageLevel,
			@RequestParam(required = false, name = "startDate") String startDateStr,
			@RequestParam(required = false, name = "endDate") String endDateStr,
			@RequestParam(required = false, name = "failureDateStart") String failureDateStartStr,
			@RequestParam(required = false, name = "failureDateEnd") String failureDateEndStr) {
		ModelAndView view = new ModelAndView("/repairRecord/contentTBody");

		if (pageSize == 0) {
			pageSize = Contains.PAGE_SIZE;
		}

		Date startDate = null, endDate = null, failureDateStart = null, failureDateEnd = null;

		try {
			if (StringUtils.isNotBlank(startDateStr))
				startDate = Contains.DAY_FMT_SDF.parse(startDateStr);
			if (StringUtils.isNotBlank(endDateStr))
				endDate = Contains.DAY_FMT_SDF.parse(endDateStr);
			if (StringUtils.isNotBlank(failureDateStartStr))
				failureDateStart = Contains.DAY_FMT_SDF.parse(failureDateStartStr);
			if (StringUtils.isNotBlank(failureDateEndStr))
				failureDateEnd = Contains.DAY_FMT_SDF.parse(failureDateEndStr);
		} catch (java.text.ParseException e) {
			logger.error(e.getMessage(), e);
		}

		Page<CustomRepairRecord> page = repairRecordService.selectPage(pageNum, pageSize, customerName, repairType,
				voltageLevel, startDate, endDate, failureDateStart, failureDateEnd);

		view.addObject("page", page);

		logger.debug(page);

		return view;
	}

	@RequestMapping("/preview")
	public ModelAndView preview(String seqId) {
		ModelAndView view = new ModelAndView("/repairRecord/preview");

		if (StringUtils.isNotBlank(seqId)) {
			CustomRepairRecord repairRecord = repairRecordService.queryCustomRepairRecord(seqId);

			view.addObject("repairRecord", repairRecord);

			// 将参数转换成map方便前台使用
			if (Contains.VOLTAGE_LOSS_CODE.equals(repairRecord.getRepairTypeCode())) {
				Map<String, String> parameterMap = parameterListToMap(recordParameterService.getParams(seqId));

				view.addObject("repairRecordParameter", parameterMap);

				if (parameterMap.size() > 0) {
					try {
						view.addObject("calculateParameter", parameterCalculate(parameterMap));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}
		}

		return view;
	}

	@RequestMapping("/detail")
	public ModelAndView detail(String seqId) {
		ModelAndView view = new ModelAndView("/repairRecord/form");

		if (StringUtils.isNotBlank(seqId)) {
			CustomRepairRecord repairRecord = repairRecordService.queryCustomRepairRecord(seqId);

			view.addObject("repairRecord", repairRecord);

			// 将参数转换成map方便前台使用
			if (Contains.VOLTAGE_LOSS_CODE.equals(repairRecord.getRepairTypeCode())) {
				Map<String, String> parameterMap = parameterListToMap(recordParameterService.getParams(seqId));
				
				String checkParam = checkParam(parameterMap);
				
				/** 校验通过计算结果 */
				if (checkParam == null) {

					if (parameterMap.size() > 0) {
						try {
							view.addObject("calculateParameter", parameterCalculate(parameterMap));
						} catch (ParseException e) {
							e.printStackTrace();
						}
					}
				}

				view.addObject("repairRecordParameter", parameterMap);
			}
		}

		List<RepairType> allRepairType = repairTypeService.selectAllRepairType();
		List<VoltageLevel> allVoltageLevel = voltageLevelService.selectAllVoltageLevel();

		view.addObject("allRepairType", allRepairType);
		view.addObject("allVoltageLevel", allVoltageLevel);

		return view;
	}

	@RequestMapping("/insert")
	@ResponseBody
	public Map<String, String> insert(String repairType, String customerNumber, String voltageLevel,
			String repairResult, @RequestParam(name = "repairDate") String repairDateStr,
			@RequestParam(name = "failureDate") String failureDateStr,
			@RequestParam(required = false, name = "params") String paramsStr,
			@RequestParam(required = false, name = "imgSeqIdstr") String imgSeqIdstr) {
		Map<String, String> result = new HashMap<String, String>();
		result.put("flag", "failed");
		result.put("msg", "新增数据失败");

		RepairRecord dmlObj = new RepairRecord();

		dmlObj.setCustomerNumber(customerNumber);

		Date repairDate = null, failureDate = null;

		try {
			if (StringUtils.isNotBlank(repairDateStr))
				repairDate = Contains.DAY_FMT_SDF.parse(repairDateStr);
			if (StringUtils.isNotBlank(failureDateStr))
				failureDate = Contains.DAY_FMT_SDF.parse(failureDateStr);
		} catch (java.text.ParseException e) {
			logger.error(e.getMessage(), e);
		}

		dmlObj.setRepairDate(repairDate);
		dmlObj.setFailureDate(failureDate);
		dmlObj.setRepairResult(repairResult);
		dmlObj.setRepairType(repairType);
		dmlObj.setSeqId(CommonStringUtils.getUUID());
		dmlObj.setVoltageLevel(voltageLevel);

		// 校验数据有效性
		String validateResult = validate(dmlObj);

		if ("RT_NP".equals(validateResult)) {
			result.put("msg", "故障类型不能为空");
		} else if ("ID_NP".equals(validateResult)) {
			logger.error("新增故障记录的时候主键为空");
		} else if ("RD_NP".equals(validateResult)) {
			result.put("msg", "恢复日期不能为空");
		} else if ("FD_NP".equals(validateResult)) {
			result.put("msg", "故障日期不能为空");
		} else if ("CN_NP".equals(validateResult)) {
			result.put("msg", "户号不能为空");
		} else if ("VL_NP".equals(validateResult)) {
			result.put("msg", "电压等级不能为空");
		} else if ("RR_NP".equals(validateResult)) {
			result.put("msg", "处理结果不能为空");
		} else if ("success".equals(validateResult)) {
			result.put("flag", validateResult);

			// 所有的校验通过后才开始保存
			try {
				// 如果故障类型是失压，校验参数
				if (Contains.VOLTAGE_LOSS_CODE.equals(Contains.REPAIR_TYPE_ID_CODE.get(repairType))) {
					Map<String, String> params = new Gson().fromJson(paramsStr,
							new TypeToken<HashMap<String, String>>() {
							}.getType());

					/* 直接保存不校验
					 * String checkParam = checkParam(params);
					if (checkParam != null) {
						result.put("flag", "failed");
						result.put("msg", checkParam);
					} else 
						
					}*/

					if (params != null) {
						// 保存附带参数
						List<RepairRecordParameter> insertParamList = new ArrayList<RepairRecordParameter>();
	
						Set<Entry<String, String>> entrySet = params.entrySet();
						Iterator<Entry<String, String>> iterator = entrySet.iterator();
						while (iterator.hasNext()) {
							Entry<String, String> next = iterator.next();
	
							RepairRecordParameter parameter = new RepairRecordParameter();
							parameter.setParameterName(next.getKey());
							parameter.setParameterValue(next.getValue());
							parameter.setRepairRecordId(dmlObj.getSeqId());
	
							insertParamList.add(parameter);
						}
	
						recordParameterService.insertBatch(insertParamList, Contains.BATCH_SIZE);
					}
				}

				if ("fai/led".equals(result.get("flag"))) {
					return result;
				}
				
				logger.debug(dmlObj);
				repairRecordService.insert(dmlObj);

				// 更新附件的所属主键ID
				String[] imgSeqIds = StringUtils.isNotBlank(imgSeqIdstr) ? imgSeqIdstr.split("@#@") : null;
				if (imgSeqIds != null && imgSeqIds.length > 0) {
					StringBuilder sb = new StringBuilder();
					int length = imgSeqIds.length;
					for (String attachmentId : imgSeqIds) {
						sb.append(attachmentId);
						if (--length > 0) {
							sb.append(",");
						}
					}
					String attachmentIds = sb.toString();
					EntityWrapper<Attachment> wrapper = new EntityWrapper<Attachment>();
					wrapper.in("SEQ_ID", attachmentIds);
					wrapper.eq("DEL_FLAG", 0);

					List<Attachment> selectList = attachmentService.selectList(wrapper);
					Iterator<Attachment> iterator = selectList.iterator();
					while (iterator.hasNext()) {
						Attachment attachment = iterator.next();
						attachment.setRecordId(dmlObj.getSeqId());
					}
					attachmentService.updateBatchById(selectList, Contains.BATCH_SIZE);
				}

				result.put("msg", "新增成功");
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				result.put("flag", "failed");
			}
		}

		return result;
	}

	@RequestMapping("/update")
	@ResponseBody
	public Map<String, String> update(String seqId, String repairType, String customerNumber, String voltageLevel,
			String repairResult, @RequestParam(name = "repairDate") String repairDateStr,
			@RequestParam(name = "failureDate") String failureDateStr,
			@RequestParam(required = false, name = "params") String paramsStr,
			@RequestParam(required = false, name = "imgSeqIdstr") String imgSeqIdstr) {
		Map<String, String> result = new HashMap<String, String>();
		result.put("flag", "failed");
		result.put("msg", "更新数据失败");

		RepairRecord dmlObj = new RepairRecord();

		dmlObj.setCustomerNumber(customerNumber);

		Date repairDate = null, failureDate = null;

		try {
			if (StringUtils.isNotBlank(repairDateStr))
				repairDate = Contains.DAY_FMT_SDF.parse(repairDateStr);
			if (StringUtils.isNotBlank(failureDateStr))
				failureDate = Contains.DAY_FMT_SDF.parse(failureDateStr);
		} catch (java.text.ParseException e) {
			logger.error(e.getMessage(), e);
		}

		dmlObj.setRepairDate(repairDate);
		dmlObj.setFailureDate(failureDate);
		dmlObj.setRepairResult(repairResult);
		dmlObj.setRepairType(repairType);
		dmlObj.setSeqId(seqId);
		dmlObj.setVoltageLevel(voltageLevel);

		// 校验数据有效性
		String validateResult = validate(dmlObj);

		if ("RT_NP".equals(validateResult)) {
			result.put("msg", "故障类型不能为空");
		} else if ("ID_NP".equals(validateResult)) {
			logger.error("更新故障记录的时候主键为空");
		} else if ("RD_NP".equals(validateResult)) {
			result.put("msg", "恢复日期不能为空");
		} else if ("FD_NP".equals(validateResult)) {
			result.put("msg", "故障日期不能为空");
		} else if ("CN_NP".equals(validateResult)) {
			result.put("msg", "户号不能为空");
		} else if ("VL_NP".equals(validateResult)) {
			result.put("msg", "电压等级不能为空");
		} else if ("RR_NP".equals(validateResult)) {
			result.put("msg", "处理结果不能为空");
		} else if ("success".equals(validateResult)) {
			result.put("flag", validateResult);

			// 所有的校验通过后才开始保存
			try {
				// 如果故障类型是失压，校验参数
				if (Contains.VOLTAGE_LOSS_CODE.equals(Contains.REPAIR_TYPE_ID_CODE.get(repairType))) {
					Map<String, String> params = new Gson().fromJson(paramsStr,
							new TypeToken<HashMap<String, String>>() {
							}.getType());

					/*直接保存不校验
					 * String checkParam = checkParam(params);
					if (checkParam != null) {
						result.put("flag", "failed");
						result.put("msg", checkParam);
					} else */
						
					if (params != null) {
						// 保存附带参数之前先删除所有的附带参数
						EntityWrapper<RepairRecordParameter> wrapper = new EntityWrapper<RepairRecordParameter>();
						wrapper.eq("repair_record_id", dmlObj.getSeqId());
						recordParameterService.delete(wrapper);

						// 保存附带参数
						List<RepairRecordParameter> insertParamList = new ArrayList<RepairRecordParameter>();

						Set<Entry<String, String>> entrySet = params.entrySet();
						Iterator<Entry<String, String>> iterator = entrySet.iterator();
						while (iterator.hasNext()) {
							Entry<String, String> next = iterator.next();

							RepairRecordParameter parameter = new RepairRecordParameter();
							parameter.setParameterName(next.getKey());
							parameter.setParameterValue(next.getValue());
							parameter.setRepairRecordId(dmlObj.getSeqId());

							insertParamList.add(parameter);
						}

						recordParameterService.insertBatch(insertParamList, Contains.BATCH_SIZE);
					}
				}

				if ("failed".equals(result.get("flag"))) {
					return result;
				}

				logger.debug(dmlObj);
				repairRecordService.updateById(dmlObj);

				// 更新附件的所属主键ID
				String[] imgSeqIds = StringUtils.isNotBlank(imgSeqIdstr) ? imgSeqIdstr.split("@#@") : null;
				if (imgSeqIds != null && imgSeqIds.length > 0) {
					StringBuilder sb = new StringBuilder();
					int length = imgSeqIds.length;
					for (String attachmentId : imgSeqIds) {
						sb.append(attachmentId);
						if (--length > 0) {
							sb.append(",");
						}
					}
					String attachmentIds = sb.toString();
					EntityWrapper<Attachment> wrapper = new EntityWrapper<Attachment>();
					wrapper.in("SEQ_ID", attachmentIds);
					wrapper.eq("DEL_FLAG", 0);

					List<Attachment> selectList = attachmentService.selectList(wrapper);
					Iterator<Attachment> iterator = selectList.iterator();
					while (iterator.hasNext()) {
						Attachment attachment = iterator.next();
						attachment.setRecordId(dmlObj.getSeqId());
					}
					attachmentService.updateBatchById(selectList, Contains.BATCH_SIZE);
				}

				result.put("msg", "更新成功");
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				result.put("flag", "failed");
			}
		}

		return result;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(String seqId) {
		try {
			repairRecordService.deleteById(seqId);
			return "success";
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return "DB_ER";
		}
	}

	@RequestMapping("/customerList")
	public ModelAndView customerList(@RequestParam(defaultValue = "1", name = "pageNum") int pageNum,
			@RequestParam(defaultValue = "0") int pageSize, String keyword) {
		if (pageSize == 0) {
			pageSize = Contains.MOVE_PAGE_SIZE;
		}

		ModelAndView view = new ModelAndView("/repairRecord/customerListTable");

		if (pageSize == 0) {
			pageSize = Contains.PAGE_SIZE;
		}

		Page<Customer> page = customerService.selectPage(pageNum, pageSize, keyword);

		view.addObject("page", page);

		view.addObject("keyword", keyword);

		logger.debug(page);

		return view;
	}

	/**
	 * @param seqId
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/exportCalculate")
	public void exportCalculate(String seqId,HttpServletRequest request,HttpServletResponse response) {
		if (StringUtils.isNotBlank(seqId)) {
			CustomRepairRecord repairRecord = repairRecordService.queryCustomRepairRecord(seqId);

			// 将参数转换成map方便前台使用
			if (Contains.VOLTAGE_LOSS_CODE.equals(repairRecord.getRepairTypeCode())) {
				Map<String, String> parameterMap = parameterListToMap(recordParameterService.getParams(seqId));
				
				ServletOutputStream outputStream = null;
				
				if (parameterMap.size() > 0) {
					try {
						Map<String, Object> calculateMap = parameterCalculate(parameterMap);
						double[] resultArray = (double[]) calculateMap.get("resultArray");

						StringBuilder strbd = new StringBuilder();

						strbd.append("故障前日历天数：[ ");
						strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[4][0]));
						strbd.append(" - ");
						strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[4][1]));
						strbd.append(" ] => ");
						strbd.append(calculateMap.get("days1"));
						strbd.append("天\r\n\r\n");

						strbd.append("故障日历天数：[ ");
						strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[4][1]));
						strbd.append(" - ");
						strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[4][2]));
						strbd.append(" ] => ");
						strbd.append(calculateMap.get("days2"));
						strbd.append("天\r\n\r\n");

						strbd.append("故障后日历天数：[ ");
						strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[4][2]));
						strbd.append(" - ");
						strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[4][3]));
						strbd.append(" ] => ");
						strbd.append(calculateMap.get("days3"));
						strbd.append("天\r\n\r\n");
						strbd.append("------------------------------------------------\r\n\r\n");

						for (int i = 0; i < Contains.VOLTAGE_LOSS_PARAM[0].length; i++) {
							strbd.append(Contains.VOLTAGE_LOSS_PARAM_CN[0][i].replaceAll("日期\\d+对应的", "日均"));
							strbd.append("：\t(");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[1][i]));
							strbd.append(" - ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[0][i]));
							strbd.append(") * ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[5][0]));
							strbd.append(" * ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[5][1]));
							strbd.append(" / ");
							strbd.append(calculateMap.get("days1"));
							strbd.append(" = ");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("avg1"));
							strbd.append("kWh/天\r\n\r\n");

							strbd.append(Contains.VOLTAGE_LOSS_PARAM_CN[2][i].replaceAll("日期\\d+对应的", "日均"));
							strbd.append("：\t(");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[3][i]));
							strbd.append(" - ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[2][i]));
							strbd.append(") * ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[5][0]));
							strbd.append(" * ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[5][1]));
							strbd.append(" / ");
							strbd.append(calculateMap.get("days3"));
							strbd.append(" = ");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("avg3"));
							strbd.append("kWh/天\r\n\r\n");

							String temp = Contains.VOLTAGE_LOSS_PARAM_CN[2][i].replaceAll("日期\\d+对应的", "日均");
							strbd.append(temp.substring(temp.indexOf("日均"), temp.length()));
							strbd.append("：\t(");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("avg3"));
							strbd.append(" + ");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("avg1"));
							strbd.append(") / 2");
							strbd.append(" = ");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("avg2"));
							strbd.append("kWh/天\r\n\r\n");

							strbd.append("故障期间损失");
							strbd.append(temp.substring(temp.indexOf("日均") + 2, temp.length()));
							strbd.append("：\t");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("avg2"));
							strbd.append(" * ");
							strbd.append(calculateMap.get("days2"));
							strbd.append(" = ");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("lossResult"));
							strbd.append("kWh\r\n\r\n");

							strbd.append("故障期间计收");
							strbd.append(temp.substring(temp.indexOf("日均") + 2, temp.length()));
							strbd.append("：\t ( ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[2][i]));
							strbd.append(" - ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[1][i]));
							strbd.append(" ) * ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[5][0]));
							strbd.append(" * ");
							strbd.append(parameterMap.get(Contains.VOLTAGE_LOSS_PARAM[5][1]));
							strbd.append(" = ");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("tempResult"));
							strbd.append("kWh\r\n\r\n");

							strbd.append("故障期间后追补");
							strbd.append(temp.substring(temp.indexOf("日均") + 2, temp.length()));
							strbd.append("：\t");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("lossResult"));
							strbd.append(" - ");
							strbd.append(((Map<String, Object>) calculateMap.get("array" + (i + 1))).get("tempResult"));
							strbd.append(" = ");
							strbd.append(resultArray[i]);
							strbd.append("kWh\r\n\r\n");
							
							strbd.append("------------------------------------------------\r\n\r\n");
						}
						
						strbd.append("故障期间后追补电量[平]：\t");
						for(int i = 0;i < resultArray.length - 1;i++){
							strbd.append(resultArray[i]);
							if(i < resultArray.length - 2){
								strbd.append(" - ");
							}
							else{
								strbd.append(" = ");
							}
						}
						strbd.append(resultArray[resultArray.length - 1]);
						strbd.append("kWh\r\n\r\n");

						logger.debug(strbd.toString());
						
						response.setCharacterEncoding("utf-8");
			            //设置响应内容的类型
			            response.setContentType("text/plain");
			            //设置文件的名称和格式
			            response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(CALCULATE_EXPORT_FILE_NAME,"UTF-8"));//通过后缀可以下载不同的文件格式
			            
			            outputStream = response.getOutputStream();
			            outputStream.write(strbd.toString().getBytes());
			            
					} catch (ParseException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if(outputStream != null){
							try {
								outputStream.close();
							} catch (IOException e) {
								logger.error(e.getMessage(),e);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * @param imageId
	 * @return
	 */
	@RequestMapping("/delAttachment")
	@ResponseBody
	public boolean delAttachment(String imageId) {
		try {
			Attachment attachment = new Attachment();

			attachment.setSeqId(imageId);
			attachment.setDelFlag(1);

			attachmentService.updateById(attachment);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 校验故障记录参数是否有效
	 * 
	 * @param repairRecord
	 * @return
	 */
	private String validate(RepairRecord repairRecord) {
		if (StringUtils.isBlank(repairRecord.getRepairType())) {
			return "RT_NP";
		}
		if (StringUtils.isBlank(repairRecord.getSeqId())) {
			return "ID_NP";
		}
		if (repairRecord.getRepairDate() == null) {
			return "RD_NP";
		}
		if (repairRecord.getFailureDate() == null) {
			return "FD_NP";
		}
		if (StringUtils.isBlank(repairRecord.getCustomerNumber())) {
			return "CN_NP";
		}
		if (StringUtils.isBlank(repairRecord.getVoltageLevel())) {
			return "VL_NP";
		}
		if (StringUtils.isBlank(repairRecord.getRepairResult())) {
			return "RR_NP";
		}
		return "success";
	}

	/**
	 * 校验故障记录的额外参数是否有效，主要是故障类型为失压时的参数
	 * 
	 * @param params
	 * @return
	 */
	private String checkParam(Map<String, String> params) {
		if (params != null) {
			for (int i = 0; i < Contains.VOLTAGE_LOSS_PARAM_REQUIRED.length; i++) {
				boolean[] requiredArray1 = Contains.VOLTAGE_LOSS_PARAM_REQUIRED[i];
				for (int j = 0; j < requiredArray1.length; j++) {
					boolean required = requiredArray1[j];
					if (required && StringUtils.isBlank(params.get(Contains.VOLTAGE_LOSS_PARAM[i][j]))) {
						return Contains.VOLTAGE_LOSS_PARAM_CN[i][j] + "不能为空";
					}
				}
			}
		}
		return null;
	}

	private Map<String, String> parameterListToMap(List<RepairRecordParameter> parameterList) {
		Map<String, String> resultMap = new HashMap<String, String>();

		if (parameterList != null) {
			Iterator<RepairRecordParameter> iterator = parameterList.iterator();
			while (iterator.hasNext()) {
				RepairRecordParameter next = iterator.next();

				resultMap.put(next.getParameterName(), next.getParameterValue());
			}
		}
		return resultMap;
	}

	private Map<String, Object> parameterCalculate(Map<String, String> parameterMap) throws ParseException {
		Map<String, Object> parameterResult = new HashMap<String, Object>();

		String[][] keyArray = Contains.VOLTAGE_LOSS_PARAM;

		double days1 = Math.ceil((Contains.DAY_FMT_SDF.parse(parameterMap.get(keyArray[4][1])).getTime()
				- Contains.DAY_FMT_SDF.parse(parameterMap.get(keyArray[4][0])).getTime()) / 1000 / 60 / 60
				/ 24);
		double days2 = Math.ceil((Contains.DAY_FMT_SDF.parse(parameterMap.get(keyArray[4][2])).getTime()
				- Contains.DAY_FMT_SDF.parse(parameterMap.get(keyArray[4][1])).getTime()) / 1000 / 60 / 60
				/ 24);
		double days3 = Math.ceil((Contains.DAY_FMT_SDF.parse(parameterMap.get(keyArray[4][3])).getTime()
				- Contains.DAY_FMT_SDF.parse(parameterMap.get(keyArray[4][2])).getTime()) / 1000 / 60 / 60
				/ 24);

		// 将三个时间差添加到结果map中
		parameterResult.put("days1", days1);
		parameterResult.put("days2", days2);
		parameterResult.put("days3", days3);

		double[] resultArray = new double[keyArray[0].length + 1];

		for (int i = 0; i < keyArray[0].length; i++) {
			Map<String, Object> tempMap = new HashMap<String, Object>();

			double temp1 = Double.parseDouble(parameterMap.get(keyArray[1][i]))
					- Double.parseDouble(parameterMap.get(keyArray[0][i]));
			double temp2 = Double.parseDouble(parameterMap.get(keyArray[2][i]))
					- Double.parseDouble(parameterMap.get(keyArray[1][i]));
			double temp3 = Double.parseDouble(parameterMap.get(keyArray[3][i]))
					- Double.parseDouble(parameterMap.get(keyArray[2][i]));

			double avg1 = days1 == 0 ? 0 : temp1 * Double.parseDouble(parameterMap.get(keyArray[5][0]))
					* Double.parseDouble(parameterMap.get(keyArray[5][1])) / days1;
			avg1 = Math.round(avg1 * 100) / 100.0;
			
			double avg3 = days3 == 0 ? 0 : temp3 * Double.parseDouble(parameterMap.get(keyArray[5][0]))
					* Double.parseDouble(parameterMap.get(keyArray[5][1])) / days3;
			avg3 = Math.round(avg3 * 100) / 100.0;
			
			double avg2 = (avg1 + avg3) / 2;
			avg2 = Math.round(avg2 * 100) / 100.0;
			
			double lossResult = avg2 * days2;
			lossResult = Math.round(lossResult * 100) / 100.0;
			
			double tempResult = temp2 * Double.parseDouble(parameterMap.get(keyArray[5][0]))
					* Double.parseDouble(parameterMap.get(keyArray[5][1]));
			tempResult = Math.round(tempResult * 100) / 100.0;
			
			double result = lossResult - tempResult;
			result = Math.round(result * 100) / 100.0;

			// 将各个计算结果放入到结果map中
			tempMap.put("temp1", temp1);
			tempMap.put("temp2", temp2);
			tempMap.put("temp3", temp3);

			tempMap.put("avg1", avg1);
			tempMap.put("avg3", avg3);
			tempMap.put("avg2", avg2);

			tempMap.put("lossResult", lossResult);
			tempMap.put("tempResult", tempResult);

			parameterResult.put("array" + (i + 1), tempMap);

			resultArray[i] = result;
		}
		
		resultArray[resultArray.length - 1] = resultArray[0];
		
		for(int i = 1;i < resultArray.length - 1;i++){
			resultArray[resultArray.length - 1] -= resultArray[i];
		}
		
		parameterResult.put("resultArray", resultArray);

		return parameterResult;
	}
}
